Imports Cdm.DataCore.Budget
Imports Cdm.DataCore.LookupTables
Imports Cdm.DataCore.CaseNotes

Partial Class Budget_SpendingPlanView
    Inherits System.Web.UI.Page

    Private Property ConfirmSpendingPlanFileName() As String
        Get
            If ViewState("spendingplanfilename") Is Nothing Then
                Return ""
            Else
                Return ViewState("spendingplanfilename")
            End If
        End Get
        Set(ByVal value As String)
            ViewState("spendingplanfilename") = value
        End Set
    End Property

    Private Property ConfirmSpendingPlan() As Cdm.DataCore.Budget.SpendingPlan
        Get
            If ViewState("uploadspendingplan") Is Nothing Then
                Return Nothing
            Else
                Return CType(ViewState("uploadspendingplan"), Cdm.DataCore.Budget.SpendingPlan)
            End If
        End Get
        Set(ByVal value As Cdm.DataCore.Budget.SpendingPlan)
            ViewState("uploadspendingplan") = value
        End Set
    End Property

    Private Property SortExpression() As String
        Get
            If ViewState("SortExpression") Is Nothing Then
                ViewState("SortExpression") = "DateModified"
            End If
            Return ViewState("SortExpression")
        End Get
        Set(ByVal value As String)
            If value.Equals(Me.SortExpression) Then
                ToggleSortDirection()
            Else
                ViewState("SortDirection") = " ASC"
            End If
            ViewState("SortExpression") = value
        End Set
    End Property

    Private Sub ToggleSortDirection()
        If ViewState("SortDirection").Equals(" DESC") Then
            ViewState("SortDirection") = " ASC"
        Else
            ViewState("SortDirection") = " DESC"
        End If
    End Sub

    Private ReadOnly Property SortDirection() As String
        Get
            Return ViewState("SortDirection")
        End Get
    End Property

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Dim Participant As New Cdm.DataCore.Entities.Participant()
        Dim spendingPlanId As Integer
        If Request("id") Is Nothing Then
            spendingPlanId = 0
        Else
            spendingPlanId = Convert.ToInt32(Request("id"))
        End If

        Participant = EntityController.GetParticipant()
        If Participant Is Nothing Then
            maindiv.Visible = False

            'ParticipantNameTwoLabel.Text = "There is no participant associated with this user."
        Else
        End If
    End Sub

    Private Sub BindSpendingPlanDetails(ByVal participantId As Integer, ByVal spendingplanId As Integer)
        Me.SpendingPlanDetailsGridView.DataSource = Cdm.DataCore.Budget.SpendingPlanSummary.Retrieve(participantId, spendingplanId)
        Me.SpendingPlanDetailsGridView.DataBind()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load
        SetupJavascript()
        Dim Participant As New Cdm.DataCore.Entities.Participant()
        Participant = EntityController.GetParticipant()
        EntityController.SetSubNavTabsFinancial(Me.EditCaseSubNav)
        EntityController.SetFinancialTab(Me.FinancialSubName, Me.EditCaseSubNav)
        'SpendingPlanLabel.Text = EntityController.ReplaceDisplayName("Spending Plan")
        Dim SpendingPlanListLabel As Label = Me.SpendingPlanAccordion.Panes(0).FindControl("SpendingPlanListLabel")
        SpendingPlanListLabel.Text = String.Concat("List of ", _
                    EntityController.ReplaceDisplayName("Spending Plan"), _
                    "s for ", Participant.DisplayLastNameFirst)

        Dim mm As MasterPageExpandable = Me.Master
        mm.SetResizeDivs(False)

        If Not Me.IsPostBack Then
            BindGrid()
            Dim spendingPlanId As Integer
            If Request("id") Is Nothing Then
                spendingPlanId = 0
            Else
                spendingPlanId = Convert.ToInt32(Request("id"))
            End If

            BindSpendingPlanDetails(Participant.ParticipantId, spendingPlanId)
            UserAuthorization.CheckPagePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseSpendingPlan, "VIEW")
            DenialReasonDropDownList.DataSource = Cdm.DataCore.LookupTables.LuSpendingPlanDenialReason.ListAll(0, "Select Denial Reason...")
            DenialReasonDropDownList.DataTextField = "Description"
            DenialReasonDropDownList.DataValueField = "DenialReasonId"
            DenialReasonDropDownList.DataBind()
        End If


        If Participant Is Nothing Then
            maindiv.Visible = False
        Else
            GetSpendingPlanData(Participant, 0)
        End If

    End Sub




    Private Sub SetupJavaScript()
        EntityController.JavaScriptSetFixedHeight(0)
        'EntityController.JavaScriptAddChildDiv(Me.maindiv.ClientID, 125)
        'EntityController.JavaScriptAddChildDiv(Me.pageDiv.ClientID, 125)
    End Sub

    Protected Sub SpendingPlansGridView_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles SpendingPlansGridView.PageIndexChanging
        SpendingPlansGridView.PageIndex = e.NewPageIndex
        BindGrid()
    End Sub

    Protected Sub SpendingPlansGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles SpendingPlansGridView.RowCancelingEdit
        SpendingPlansGridView.EditIndex = -1
        BindGrid()
    End Sub

    Protected Sub SpendingPlansGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles SpendingPlansGridView.RowUpdating

        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId
        Dim spendingplanId As Integer = Convert.ToInt32(SpendingPlansGridView.DataKeys(e.RowIndex).Value)
        Dim newStartDate As DateTime, oldStartDate As DateTime
        Dim newEndDate As DateTime, oldEndDate As DateTime
        Dim newStatusId As Integer, oldStatusId As Integer
        Dim updateSpendingPlan As SpendingPlan = SpendingPlan.Retrieve(spendingplanId)

        'Get the controls on the edited row for start date, end date, status
        Dim startDateTextBox As TextBox = CType(SpendingPlansGridView.Rows(e.RowIndex).FindControl("EditStartDateTextBox"), TextBox)
        Dim endDateTextBox As TextBox = CType(SpendingPlansGridView.Rows(e.RowIndex).FindControl("EditEndDateTextBox"), TextBox)
        Dim statusDropDown As DropDownList = CType(SpendingPlansGridView.Rows(e.RowIndex).FindControl("EditStatusDropDownList"), DropDownList)
        Dim commentsTextBox As TextBox = CType(SpendingPlansGridView.Rows(e.RowIndex).FindControl("CommentsTextBox"), TextBox)

        Dim errorMessage As String = ""
        If Not DatesValid(startDateTextBox, endDateTextBox, errorMessage) Then
            FormError("Can Not update", errorMessage)
            Exit Sub
        Else
            'Retrieve the old data, so that we can tell what has changed
            'and what notifications will need to be sent.
            oldStartDate = updateSpendingPlan.StartDate
            oldEndDate = updateSpendingPlan.EndDate
            oldStatusId = updateSpendingPlan.SpendingPlanStatusId

            newStartDate = Convert.ToDateTime(startDateTextBox.Text)
            newEndDate = Convert.ToDateTime(endDateTextBox.Text)
            newStatusId = Convert.ToInt32(statusDropDown.SelectedValue)

            updateSpendingPlan.StartDate = newStartDate
            updateSpendingPlan.EndDate = newEndDate
            updateSpendingPlan.SpendingPlanStatusId = newStatusId

        End If

        'If the status has been changed to Denied, set the boolean
        Dim bSpendingPlanDenied As Boolean = False
        If newStatusId = Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Denied And _
           newStatusId <> oldStatusId Then
            bSpendingPlanDenied = True
        End If

        Dim versionNumber As Integer
        Dim spValidate As SpendingPlan.DateValidationType = updateSpendingPlan.CheckDatesValid(participantId, errorMessage, versionNumber)
        Select Case spValidate
            Case SpendingPlan.DateValidationType.DateMatchesAnotherStartDate
                If oldStartDate <> newStartDate Then
                    ShowConfirmMessage(errorMessage, bSpendingPlanDenied, oldStartDate, oldEndDate, oldStatusId)
                    Me.ConfirmSpendingPlan = updateSpendingPlan
                    Me.ConfirmSpendingPlanFileName = ""
                    Exit Sub
                Else
                    'Do not show a confirm message if user did not modify the start date
                    Exit Select
                End If
            Case SpendingPlan.DateValidationType.DatesOverlap
                FormError("Can not Update", errorMessage)
                Exit Sub
            Case SpendingPlan.DateValidationType.ErrorOccurred
                FormError("Can Not update", errorMessage)
                Exit Sub
            Case SpendingPlan.DateValidationType.DatesAreValid
                Exit Select

        End Select

        If (bSpendingPlanDenied) Then
            ShowConfirmMessage("", bSpendingPlanDenied, oldStartDate, oldEndDate, oldStatusId)
            Me.ConfirmSpendingPlan = updateSpendingPlan
            Exit Sub
        Else
            updateSpendingPlan.Persist()

            If oldStartDate <> newStartDate Or oldEndDate <> newEndDate Then
                updateSpendingPlan.UpdateItemDates()
            End If
            SendNotifications(oldStartDate, oldEndDate, oldStatusId, newStartDate, newEndDate, newStatusId)
            SpendingPlansGridView.EditIndex = -1
            BindGrid()
        End If


    End Sub


    Private Sub ShowConfirmMessage(ByVal errorMessage As String)
        FormError("Confirm", errorMessage)
        Me.UploadConfirmPanel.Visible = True

    End Sub

    Private Sub ShowConfirmMessage(ByVal errorMessage As String, ByVal bSpendingPlanDenied As Boolean, _
                                ByVal oldStartDate As DateTime, ByVal oldEndDate As DateTime, ByVal oldStatusId As Integer)



        ShowConfirmMessage(errorMessage)
        'Add the old values to the ViewState for retrieval on confirm, to determine
        'what notifications need to be sent.
        ViewState("oldStartDate") = oldStartDate
        ViewState("oldEndDate") = oldEndDate
        ViewState("oldStatusId") = oldStatusId

    End Sub

    Private Function DatesValid(ByVal startDateTextBox As TextBox, ByVal endDateTextBox As TextBox, _
                                ByRef errorMessage As String) As Boolean

        If startDateTextBox Is Nothing Or endDateTextBox Is Nothing Then
            errorMessage = "Unable to read data"
            Return False
        End If

        'Check that both textboxes contain valid dates.
        If Not (IsDate(startDateTextBox.Text) And IsDate(endDateTextBox.Text)) Then
            errorMessage = "Please check that start and end dates are valid dates."
            Return False
        End If

        'Check that start date is not later than end date
        If CDate(startDateTextBox.Text) > CDate(endDateTextBox.Text) Then
            errorMessage = "Start date may not be later than end date."
            Return False
        End If

        Return True
    End Function


    Public Function GetActiveImage(ByVal isActive As Boolean) As String
        If isActive Then
            Return "~/Images/GreenCheck.gif"
        Else
            Return "~/Images/Blank1x1.gif"
        End If
    End Function

    Public Function GetStatusColor(ByVal statusId As Integer) As String
        Select Case statusId
            Case Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Approved
                Return "green"
            Case Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Denied
                Return "red"
            Case Else
                Return "black"
        End Select
    End Function

    Private Sub FormError(ByVal title As String, ByVal errorMessage As String)
        Me.PopupMessage1.ShowErrorMessage(title, errorMessage)
    End Sub

    Private Sub SendNotifications(ByVal oldStartDate As DateTime, ByVal oldEndDate As DateTime, ByVal oldStatusId As Integer, _
                                ByVal newStartDate As DateTime, ByVal newEndDate As DateTime, ByVal newStatusId As Integer)

        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId
        'Check if the status has changed
        'If the status is changned to:  approve, send a Spendingplanapproved notification
        '                               Denied - then send a SpendingPlanRejected notification
        '                               Submitted - then send a SpendingPlanSubmittedForApproval
        If oldStatusId <> newStatusId Then
            If newStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Approved Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanApproved, participantId)
            End If
            If newStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Denied Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanRejected, participantId)
            End If

            If newStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Submitted Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanSubmittedForApproval, participantId)
            End If
        End If

        'If the startdate or enddate has changed, and the spending plan was previously approved,
        'then send the previousapproved spending plan has had dates changed notification
        If (Not oldStartDate.ToShortDateString().Equals(newStartDate.ToShortDateString())) Or _
           (Not oldEndDate.ToShortDateString().Equals(newEndDate.ToShortDateString())) Then
            If oldStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Approved Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanPreviouslyApprovedHasDatesChanges, participantId)
            End If
        End If

    End Sub


    Private Sub BindDenialReasonDropDown()
        DenialReasonDropDownList.DataSource = Cdm.DataCore.LookupTables.LuSpendingPlanDenialReason.ListAll(0, "Select Denial Reason...")
        DenialReasonDropDownList.DataTextField = "Description"
        DenialReasonDropDownList.DataValueField = "DenialReasonId"
        DenialReasonDropDownList.DataBind()
    End Sub
    Protected Sub SpendingPlansGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles SpendingPlansGridView.RowDataBound
        Dim statusDropDown As DropDownList = CType(e.Row.FindControl("EditStatusDropDownList"), DropDownList)
        If Not statusDropDown Is Nothing Then
            statusDropDown.DataSource = StatusList()
            statusDropDown.DataBind()
            statusDropDown.SelectedValue = CStr(SpendingPlansGridView.DataKeys(e.Row.RowIndex).Item(1))
            statusDropDown.Enabled = UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseSpendingPlanApprove)
        End If
    End Sub


    Public Function StatusList() As System.Collections.Generic.List(Of Cdm.DataCore.LookupTables.LuSpendingPlanStatus)
        Return Cdm.DataCore.LookupTables.LuSpendingPlanStatus.ListAll()
    End Function

    Protected Sub SpendingPlansGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles SpendingPlansGridView.RowEditing
        SpendingPlansGridView.EditIndex = e.NewEditIndex
        BindGrid()
    End Sub

    Private Sub BindGrid()
        Dim sortBy As String = String.Concat(Me.SortExpression, Me.SortDirection)
        SpendingPlansGridView.DataSource = SpendingPlanGrid.ListByParticipant(EntityController.GetParticipant().ParticipantId, sortBy)
        SpendingPlansGridView.DataBind()
    End Sub

    Protected Sub SpendingPlanDetailsGridView_RowCommand(ByVal sender As Object, _
                                                   ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
                                                   Handles SpendingPlanDetailsGridView.RowCommand

        If IsPostBack Then
            Page.SetFocus(e.CommandSource)
        End If
        Dim gv As GridView = CType(sender, GridView)

        Dim gv2 As GridView = CType(e.CommandSource, Button).Parent.NamingContainer.FindControl("GridView6")
        gv2.AlternatingRowStyle.BackColor = Drawing.Color.FromName("#E8ECF4")
        Dim headerStyle As New Style
        headerStyle.BackColor = Drawing.Color.FromName("#949FB1")
        gv2.HeaderRow.ApplyStyle(headerStyle)

        If gv2.Visible Then
            gv2.Visible = False
        Else
            gv2.Visible = True
        End If

    End Sub

    Protected Sub GetSpendingPlanData(ByVal Participant As Cdm.DataCore.Entities.Participant, ByVal spendingPlanId As Integer)

        Dim sqlDataSource As New SqlDataSource
        Dim connectionString As String = EntityController.AppConnectString
        Dim parmParticipantId As New Parameter
        Dim parmSpendingPlanId As New Parameter
        Dim args As New DataSourceSelectArguments
        If Not UserAuthorization.HasReadOnlyPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseSpendingPlanApprove) Then
            ApproveButton.Visible = True
            RejectButton.Visible = True
            DenialReasonDropDownList.Visible = True
            DenialReasonDropDownList.Attributes.Add("onchange", String.Format("setEnabled('{0}','{1}')", DenialReasonDropDownList.ClientID, RejectButton.ClientID))
            RejectButton.Enabled = False
            'StartDateTextBox.Visible = True
            'StartDateLabel.Visible = False
            Me.ApprovedDateOfPlanTextBox.Visible = CollectApprovedDateOfPlan()
            Me.ApprovedDateOfPlanLabel.Visible = False
            Me.ApprovedDateOfPlanDescriptionLabel.Visible() = CollectApprovedDateOfPlan()
        End If
        sqlDataSource.ConnectionString = connectionString
        sqlDataSource.SelectCommand = "spGetSpendingPlanData"
        sqlDataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure

        parmParticipantId.Name = "ParticipantId"
        parmParticipantId.Type = TypeCode.Int32


        parmParticipantId.DefaultValue = Participant.ParticipantId

        parmSpendingPlanId.Name = "SpendingPlanId"
        parmSpendingPlanId.Type = TypeCode.Int32
        parmSpendingPlanId.DefaultValue = spendingPlanId

        sqlDataSource.SelectParameters.Add(parmParticipantId)
        sqlDataSource.SelectParameters.Add(parmSpendingPlanId)

        Dim dv As System.Data.DataView = sqlDataSource.Select(args)

        If dv Is Nothing Then
            maindiv.Visible = False
            'secdiv.Visible = True
        Else

            If dv.Count <> 0 Then
                Session("SpendingPlanId") = dv(0)("SpendingPlanId").ToString()
                CurrentStatusLabel.Text = dv(0)("Description").ToString()
                'SubmittedDate.Text = dv(0)("Description").ToString()
                StartDateLabel.Text = String.Format("{0:d}", dv(0)("StartDate"))
                If CollectApprovedDateOfPlan() Then
                    ApprovedDateOfPlanLabel.Text = String.Format("{0:d}", dv(0)("ApprovedDateOfPlan"))
                End If
                EffectiveDatesLabel.Text = String.Format("{0:d}", dv(0)("EffectiveDate"))
                'BudgetAmount.Text = dv(0)("BudgetAmount").ToString()
                BudgetAmount.Text = String.Format("{0:C}", dv(0)("BudgetAmount"))
                Try
                    Dim lblBalance As Label = SpendingPlanDetailsGridView.FooterRow.FindControl("lblBalance")
                    Dim amount As Double = GetAmount()
                    lblBalance.Text = String.Format("{0:C}", dv(0)("BudgetAmount") - amount)
                Catch
                End Try
                If dv(0)("SpendingPlanStatusId") <> 25001 Then
                    ApproveButton.Visible = False
                    RejectButton.Visible = False
                    DenialReasonDropDownList.Visible = False
                    StartDateTextBox.Visible = False
                    ApprovedDateOfPlanLabel.Visible = CollectApprovedDateOfPlan()
                    ApprovedDateOfPlanTextBox.Visible = False
                    StartDateLabel.Visible = True
                End If
                maindiv.Visible = True
                ' secdiv.Visible = False
            Else
                maindiv.Visible = False
                'secdiv.Visible = True
            End If

        End If

    End Sub
    ''' <summary>
    ''' Check to see if the setting for collecting the approved Date of Plan.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CollectApprovedDateOfPlan() As Boolean
        Try
            Dim showApprovedPlan As String = System.Web.HttpContext.Current.Application("CollectApprovedDateOfPlan")
            If String.IsNullOrEmpty(showApprovedPlan) Then
                Return False
            Else
                Return CBool(showApprovedPlan)
            End If
        Catch ex As Exception
            Return False
        End Try
        
    End Function

    Private Function GetAmount() As Double

        Dim sqlDataSource As New SqlDataSource
        'Dim connectionString As String = ConfigurationManager.ConnectionStrings("SpendingPlanData").ConnectionString
        Dim connectionString As String = EntityController.AppConnectString
        Dim parmParticipantId As New Data.SqlClient.SqlParameter
        Dim parmSpendingPlanId As New Data.SqlClient.SqlParameter
        Dim args As New DataSourceSelectArguments
        Dim sqlDataAdapter As New System.Data.SqlClient.SqlDataAdapter()
        Dim command As New Data.SqlClient.SqlCommand()
        Dim connection As New Data.SqlClient.SqlConnection()

        command.Connection = connection
        command.Connection.ConnectionString = connectionString
        command.CommandText = "spGetSpendingPlanSummary"
        command.CommandType = System.Data.CommandType.StoredProcedure

        parmParticipantId.ParameterName = "ParticipantId"
        parmParticipantId.SqlDbType = Data.SqlDbType.Int


        parmParticipantId.Value = EntityController.GetParticipant().ParticipantId

        parmSpendingPlanId.ParameterName = "SpendingPlanId"
        parmSpendingPlanId.SqlDbType = Data.SqlDbType.Int
        If Session("SpendingPlanId") Is Nothing Then
            parmSpendingPlanId.Value = 0
        Else
            parmSpendingPlanId.Value = Session("SpendingPlanId")
        End If

        command.Parameters.Add(parmParticipantId)
        command.Parameters.Add(parmSpendingPlanId)

        sqlDataAdapter.SelectCommand = command

        Dim ds As New System.Data.DataSet()

        sqlDataAdapter.Fill(ds)

        Return Convert.ToDouble(ds.Tables(1).Rows(0)("Total").ToString())

    End Function

    Protected Sub SpendingPlanDetailsGridView_RowDataBound(ByVal sender As Object, _
                                                     ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
                                                     Handles SpendingPlanDetailsGridView.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim gv As GridView = e.Row.FindControl("GridView6")
            Dim details As Button = e.Row.FindControl("toggleDetails")
            Dim bf As New BoundField
            Dim sqlDataSource As New SqlDataSource
            Dim parmSpendingPlanId As New Parameter
            Dim parmBudgetCategoryId As New Parameter
            Dim args As New DataSourceSelectArguments

            Dim SpendingPlanSummary As Cdm.DataCore.Budget.SpendingPlanSummary = e.Row.DataItem

            'Dim connectionString As String = ConfigurationManager.ConnectionStrings("SpendingPlanData").ConnectionString
            Dim connectionString As String = EntityController.AppConnectString

            sqlDataSource.ConnectionString = connectionString
            sqlDataSource.SelectCommand = "spGetSpendingPlanItems"
            sqlDataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure

            parmSpendingPlanId.Name = "SpendingPlanId"
            parmSpendingPlanId.Type = TypeCode.Int32
            parmSpendingPlanId.DefaultValue = SpendingPlanSummary.SpendingPlanID

            parmBudgetCategoryId.Name = "BudgetCategoryId"
            parmBudgetCategoryId.Type = TypeCode.Int32
            'parmBudgetCategoryId.DefaultValue = Session("BudgetCategoryId")
            parmBudgetCategoryId.DefaultValue = SpendingPlanSummary.BudgetCategoryId

            sqlDataSource.SelectParameters.Add(parmSpendingPlanId)
            sqlDataSource.SelectParameters.Add(parmBudgetCategoryId)

            Dim dv As Data.DataView = sqlDataSource.Select(args)

            gv.DataSource = sqlDataSource
            gv.AutoGenerateColumns = True

            If dv.Table.Rows(0).ItemArray.Length = 1 Then
                details.Visible = False
            End If

            gv.DataBind()
            gv.AlternatingRowStyle.BackColor = Drawing.Color.FromName("#E8ECF4")
            Dim headerStyle As New Style
            headerStyle.BackColor = Drawing.Color.FromName("#949FB1")
            gv.HeaderRow.ApplyStyle(headerStyle)
            gv.Visible = False

        End If

    End Sub

    Protected Sub ApproveButton_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles ApproveButton.Click

        Dim SpendPlan As Cdm.DataCore.Budget.SpendingPlan
        Dim dtApprovedDateOfPlan As DateTime

        SpendPlan = Cdm.DataCore.Budget.SpendingPlan.Retrieve(Session("SpendingPlanId"))
        SpendPlan.SpendingPlanStatusId = Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Approved

        Try
            If CollectApprovedDateOfPlan() Then
                If IsDate(ApprovedDateOfPlanTextBox.Text) Then
                    dtApprovedDateOfPlan = Convert.ToDateTime(ApprovedDateOfPlanTextBox.Text)
                    SpendPlan.ApprovedDateOfPlan = dtApprovedDateOfPlan
                Else
                    ErrorLabel.Text = "Please enter a valid Approved Date of Plan for the " + EntityController.ReplaceDisplayName("Spending Plan") + "."
                    ErrorLabel.Visible = True
                    Exit Sub
                End If
            End If
            'dtStartDate = Convert.ToDateTime(StartDateTextBox.Text)
            'SpendPlan.StartDate = dtStartDate
            SpendPlan.LastModified = UserAuthorization.CurrentUser.LogonId
            SpendPlan.DateModified = Now
            SpendPlan.Persist()
            ApproveButton.Visible = False
            RejectButton.Visible = False
            DenialReasonDropDownList.Visible = False
            StartDateTextBox.Visible = False
            StartDateLabel.Visible = True
            ErrorLabel.Text = ""
            ErrorLabel.Visible = False
        Catch ex As Exception
            ErrorLabel.Text = "Please enter a valid Start Date for the " + EntityController.ReplaceDisplayName("Spending Plan") + "."
            ErrorLabel.Visible = True
            Exit Sub
        End Try

        Dim Participant As New Cdm.DataCore.Entities.Participant()
        Participant = EntityController.GetParticipant()
        If Not Participant Is Nothing Then
            EntityController.SendNotification(Cdm.DataCore.CaseNotes.Notification.NotificationType.SpendingPlanApproved, Participant.ParticipantId)
            GetSpendingPlanData(Participant, CInt(Session("SpendingPlanId")))
        End If

    End Sub

    Protected Sub RejectButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles RejectButton.Click

        Dim SpendPlan As Cdm.DataCore.Budget.SpendingPlan
        SpendPlan = Cdm.DataCore.Budget.SpendingPlan.Retrieve(Session("SpendingPlanId"))
        SpendPlan.SpendingPlanStatusId = Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Denied
        SpendPlan.DenialReasonId = Me.DenialReasonDropDownList.SelectedValue
        SpendPlan.LastModified = UserAuthorization.CurrentUser.LogonId
        SpendPlan.DateModified = Now
        SpendPlan.Persist()
        ApproveButton.Visible = False
        RejectButton.Visible = False
        DenialReasonDropDownList.Visible = False
        Dim Participant As New Cdm.DataCore.Entities.Participant()

        Participant = EntityController.GetParticipant()
        If Not Participant Is Nothing Then
            EntityController.SendNotification(Cdm.DataCore.CaseNotes.Notification.NotificationType.SpendingPlanRejected, Participant.ParticipantId)
            GetSpendingPlanData(Participant, SpendPlan.SpendingPlanId)
        End If

        Response.Redirect("~/Case/CasePersonal.aspx?ActiveTab=Notes&spendingplandenyreason=" & Me.DenialReasonDropDownList.SelectedValue)

    End Sub

    Protected Sub EditCaseSubNav2_ChangeMenu(ByVal sender As Object, _
                                             ByVal e As System.EventArgs) _
                                             Handles EditCaseSubNav.ChangeMenu

        EntityController.ReturnToCasePersonalPage(EditCaseSubNav)

    End Sub

    Protected Sub SpendingPlansGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles SpendingPlansGridView.RowCommand
        If e.CommandName = "View" Then
            Dim spendingPlanId As Integer = CInt(e.CommandArgument)
            BindSpendingPlanDetails(EntityController.GetParticipant.ParticipantId, spendingPlanId)
            GetSpendingPlanData(EntityController.GetParticipant(), spendingPlanId)
            Me.SpendingPlanAccordion.SelectedIndex = 1
        End If
    End Sub

    Protected Sub SpendingPlansGridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles SpendingPlansGridView.Sorting
        Me.SortExpression = e.SortExpression
        BindGrid()
    End Sub
End Class
